package com.tpv.myapp.service;

import jakarta.mail.*;
import jakarta.mail.event.MessageCountAdapter;
import jakarta.mail.event.MessageCountEvent;
import jakarta.mail.search.FlagTerm;
import jakarta.mail.search.SearchTerm;
import org.eclipse.angus.mail.imap.IMAPFolder;
import org.eclipse.angus.mail.imap.IMAPStore;
import org.eclipse.angus.mail.imap.IdleManager;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MailPullServiceIT {

    @Test
    public void pullMail() {
        try {
            Properties props = new Properties();
            props.put("mail.imap.host", "imap.126.com");
            props.put("mail.imap.port", "993");
            props.put("mail.imap.starttls.enable", "true");
            props.put("mail.imap.ssl.enable", "true");
            Session session = Session.getDefaultInstance(props);

            IMAPStore store = (IMAPStore) session.getStore("imap");
            Map<String,String> IAM = new HashMap<>();
            IAM.put("name","tpv_yjj");
            IAM.put("version","1.0.0");
            IAM.put("vendor","myapp");
            IAM.put("support-email","tpv_yjj@126.com");
            store.connect("tpv_yjj@126.com", "LAYv8Np9x6ZvZsJy");
            store.id(IAM);
            System.out.println(store.isConnected());

            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_WRITE);
            Message[] messages = inbox.getMessages();
            for (Message message : messages) {
                System.out.println(message.getSubject());
                message.setFlag(Flags.Flag.SEEN, true);
            }

            // 创建一个搜索条件，查找未读邮件
            SearchTerm searchTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            Message[] readMessages = inbox.search(searchTerm); // 搜索未读邮件
            for (Message message : readMessages) {
                System.out.println(message.getSubject());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Test(timeout = Long.MAX_VALUE)
    public void listenNewMail() {
        try {
//            ExecutorService es = Executors.newCachedThreadPool();
            Properties props = new Properties();
            props.put("mail.imap.host", "imap.qq.com");
            props.put("mail.imap.port", "993");
//            props.put("mail.imap.starttls.enable", "true");
            props.put("mail.imap.ssl.enable", "true");
//            props.put("mail.imap.usesocketchannels", "true");
//            props.put("mail.event.scope", "session"); // or "application"
//            props.put("mail.event.executor", es);
            Session session = Session.getDefaultInstance(props);
            session.setDebug(true);
//            final IdleManager idleManager = new IdleManager(session, es);
            IMAPStore store = (IMAPStore) session.getStore("imap");
            Map<String,String> IAM = new HashMap<>();
            IAM.put("name","tpv_yjj");
            IAM.put("version","1.0.0");
            IAM.put("vendor","myapp");
            IAM.put("support-email","yjj_0596@qq.com");
            store.connect("yjj_0596@qq.com", "cbgpyzdiujqucbjd");
            store.id(IAM);
            System.out.println(store.isConnected());

            IMAPFolder inbox = (IMAPFolder)store.getFolder("INBOX");
            inbox.open(Folder.READ_WRITE);

            // 添加消息监听器
            inbox.addMessageCountListener(new MessageCountAdapter() {
                @Override
                public void messagesAdded(MessageCountEvent e) {
                    Message[] messages = e.getMessages();
                    System.out.println("Number of new messages: " + messages.length);
                    for (Message message : messages) {
                        try {
                            System.out.println("New message subject: " + message.getSubject());
                            message.setFlag(Flags.Flag.SEEN, true); // 标记为已读
                        } catch (MessagingException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            });
            while (true) {
                try {
                    inbox.idle();
                    System.out.println("IDLE ended, re-entering...");
                } catch (MessagingException e) {
                    e.printStackTrace();
                    break;
                }
            }
            //idleManager.watch(inbox);
            // 保持程序运行以持续监听新邮件
            System.out.println("Listening for new emails...");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Test(timeout = Long.MAX_VALUE)
    public void listenNewMail2() {
        try {
            Properties props = new Properties();
            props.put("mail.imap.host", "mailx.tpv-edu.com");
            props.put("mail.imap.port", "993");
            props.put("mail.imap.ssl.enable", true);
            props.put("mail.imap.usesocketchannels", true);
            // ignore ssl
            props.put("mail.imap.ssl.checkserveridentity", "false");
            props.put("mail.imap.ssl.trust", "*");

            Session session = Session.getDefaultInstance(props);
            session.setDebug(true);

            ExecutorService es = Executors.newCachedThreadPool();
            IMAPStore store = (IMAPStore) session.getStore("imap");
            Map<String,String> IAM = new HashMap<>();
            IAM.put("name","iwb007");
            IAM.put("version","1.0.0");
            IAM.put("vendor","myapp");
            IAM.put("support-email","iwb007@mailx.tpv-edu.com");
            store.connect("iwb007@mailx.tpv-edu.com", "lW3ur5YdnT8yaSf8YkKj");
            store.id(IAM);
            System.out.println(store.isConnected());

            IMAPFolder inbox = (IMAPFolder)store.getFolder("INBOX");
            inbox.open(Folder.READ_WRITE);
            final IdleManager idleManager = new IdleManager(session, es);
            // 添加消息监听器
            inbox.addMessageCountListener(new MessageCountAdapter() {
                @Override
                public void messagesAdded(MessageCountEvent e) {
                    Message[] messages = e.getMessages();
                    System.out.println("Number of new messages: " + messages.length);
                    for (Message message : messages) {
                        try {
                            System.out.println("New message subject: " + message.getSubject());
                            message.setFlag(Flags.Flag.SEEN, true); // 标记为已读
                        } catch (MessagingException ex) {
                            ex.printStackTrace();
                        }
                    }
                    try {
                        // process new messages
                        idleManager.watch(inbox); // keep watching for new messages
                    } catch (MessagingException mex) {
                        // handle exception related to the Folder
                    }
                }
            });
            idleManager.watch(inbox);
            // 保持程序运行以持续监听新邮件
            System.out.println("Listening for new emails...");
            try {
                System.in.read(); // 等待用户按回车
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
